package cn.heygod.airsql.meta;

import cn.heygod.airsql.annotation.Table;
import cn.heygod.airsql.support.KeyFunction;
import cn.heygod.airsql.util.ColumnUtil;
import cn.heygod.airsql.util.StringUtil;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @className: TableManager
 * @author: Simon
 * @description: TODO
 * @date: 2024/1/22 1:33
 * @version: 1.0
 */
public class TableManager {

    private static Map<String,String> tableNameCache = new ConcurrentHashMap<>();
    private static Map<KeyFunction,String> columnNameCache = new ConcurrentHashMap<>();

    public static String getTableName(Class modelClass){
        String tableName = tableNameCache.get(modelClass.getName());
        if(tableName == null){
            //判断有没有Table注解，如果没有，则直接使用
            if(modelClass.isAnnotationPresent((Class) Table.class)){
                Table table = (Table) modelClass.getAnnotation(Table.class);
                tableName = table.name();
            }else{
                tableName = StringUtil.camelCaseToSnakeCase(modelClass.getSimpleName());
            }
            tableNameCache.put(modelClass.getName(),tableName);
        }
        return tableName;
    }

    public static <T> String getColumnName(KeyFunction<T,?> keyFunc){
        String columnName = columnNameCache.get(keyFunc);
        if(columnName == null){
            //判断有没有Table注解，如果没有，则直接使用
            columnName = ColumnUtil.getName(keyFunc);
            columnNameCache.put(keyFunc,columnName);
        }
        return columnName;
    }


}
